iT邦幫忙

2022 iThome 鐵人賽

DAY 21
0
Software Development

離開C#新手村的最後試煉系列 第 21

# 試煉21 - LINQ 中超好用的DefaultIfEmpty

  • 分享至 

  • xImage
  •  

開始試煉

在做Linq查詢的時候 常會因為where條件後怕沒有東西了
這時候接著下Max之類的語法 就會炸例外像是這樣

var list = new List<int>() { 1, 2, 3, 4, 5 };
list.Where(x => x > 10).Min().Dump("Min");


所以還要先判斷any....等
其實DefaultIfEmpty就超好用

var list = new List<int>() { 1, 2, 3, 4, 5 };
list.Where(x => x > 10)
    .DefaultIfEmpty()
	.Min()
	.Dump("Min");


也可以改變Default,DefaultIfEmpty(-1) 這樣結果就是-1
字串也一樣

var list = new List<string>() { "a", "b", "c", "d" };
list.Where(x => x.StartsWith("z"))
    .DefaultIfEmpty("NO DATA")
    .Dump();

list.Where(x => x.StartsWith("z"))
    .DefaultIfEmpty("NO DATA")
    .First()
    .Dump();

自訂物件也可以

void Main()
{
    var prodcutList = new List<Prodcut>()
    {
        new Prodcut{ Name= "Sports & Outdoors",  Price= 1200 },
        new Prodcut{ Name= "Pet Supplies",  Price= 2400 },
        new Prodcut{ Name= "Toys & Games",  Price= 5600 }
    };

    prodcutList.Where(x => x.Price > 6000)
               .DefaultIfEmpty(new Prodcut())
               .Max(x => x.Price)
               .Dump("Max Price");
}
public class Prodcut
{
    public string Name { get; set; }
    public int Price { get; set; }
}

結束試煉

Linq 真是強大


上一篇
# 試煉20 - string 不變性
下一篇
# 試煉22 - 如何用 擴充方法 來打造可讀性程式
系列文
離開C#新手村的最後試煉30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言